<template>
    <el-select
            v-model="selected"
            :placeholder="placeholder"
            :remote-method="searchUser"
            @change="inner_change"
            @clear="clear"
            :loading="loading"
            :multiple="multiple"
            :reserve-keyword="multiple"
            clearable
            filterable
            remote>
        <el-option v-for="user in users"
                   :key="user.id"
                   :value="user.id"
                   :label="user.username"/>
    </el-select>
</template>

<script>
    import _ from 'lodash';

    let unwatch;
    export default {
        name: "project_search_user",
        props: {
            placeholder: {default: '请选择'},
            value: {},
            multiple: false,
            selectedClear: false,
        },
        data() {
            return {
                loading: false,
                users: [],
                selected: this.multiple ? [] : null,
            };
        },
        methods: {
            searchUser(str) {
                if (_.isEmpty(str))
                    return;
                this.loading = true;
                this.$http.get('/api/user', {params: {search: str}}).then(res => {
                    this.loading = false;
                    this.users = res.data.list;
                });
            },
            inner_change() {
                unwatch();
                if (!this.selected) return;
                this.$emit('change', this.selected);
                this.$emit('input', this.selected);
                if (this.selectedClear)
                    this.selected = null;
            },
            clear() {
                this.$emit('clear');
            }
        },
        mounted() {
            unwatch = this.$watch('value', val => {
                this.users.push(val);
                this.selected = val.id;
                unwatch();
            });
        }
    }
</script>

<style scoped>

</style>